import React, { useState, useEffect } from 'react';
import { Select, Button } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { isDataTypeEqual } from '../../utils/dataType';
import DataTypeDisplay from '../common/DataTypeDisplay';

const valueType = {
  INPUT_PARAM: 'INPUT_PARAM',
  VARIABLE: 'VARIABLE',
};

const columns = [
  { name: '参数名称', prop: 'source' },
  { name: '数据类型', prop: 'sourceDataType' },
  { name: '赋值', prop: 'target' },
];

const RuleSetting = styled.div`
  width: 100%;
`;

const RuleSettingHead = styled.div`
  background-color: #002f5c;
  padding: 0 1px;
  color: #9ccdff;
`;

const RuleSettingBody = styled.div`
  /* border-left: 1px solid #f2f2f2;
  border-right: 1px solid #f2f2f2; */
`;

const RuleSettingTr = styled.div`
  display: flex;
  /* border-bottom: 1px solid #f2f2f2; */
  height: 36px;
`;

const RuleSettingTd = styled.div`
  flex: 1;
  min-width: 0;
  padding: 0 6px;
  display: flex;
  align-items: center;

  &.delete-td,
  &.required-td {
    width: 40px;
    flex: none;
    justify-content: center;
  }

  &.delete-td {
    width: 20px;
    margin-right: 10px;
    & > .anticon {
      cursor: pointer;
      color: #999;
    }
  }
`;

const RuleSettingFoot = styled.div`
  text-align: center;
  padding: 6px 0;
`;

const OptionLabel = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const OptionValue = styled.span`
  float: left;
`;

const OptionName = styled.span`
  float: right;
  color: var(--ant-text-color-secondary);
  font-size: 13px;
  margin-left: 5px;
`;

const OutputRuleSetting = ({
  value,
  onChange,
  addText,
  sourceList = [],
  targetList = [],
}) => {
  const [rules, setRules] = useState([...(value || [])]);

  useEffect(() => {
    if (value !== rules) {
      setRules([...value]);
    }
  }, [value]);

  const addRule = () => {
    const newRules = [
      ...rules,
      {
        source: '',
        sourceDataType: null,
        sourceType: valueType.INPUT_PARAM,
        target: '',
        targetDataType: null,
        targetType: valueType.VARIABLE,
        required: false,
      },
    ];
    setRules(newRules);
    onChange?.(newRules);
  };

  const removeRule = (rowIndex) => {
    const newRules = [...rules];
    newRules.splice(rowIndex, 1);
    setRules(newRules);
    onChange?.(newRules);
  };

  const onTargetVarChange = (rowIndex, value) => {
    const newRules = [...rules];
    const target = value;
    const param = targetList.find(item => item.envKey === target);
    newRules[rowIndex].targetDataType = param.dataType;
    setRules(newRules);
    onChange?.(newRules);
  };

  const getAvailableSource = (source) => {
    return sourceList.filter(item => {
      if (item.paramKey === source) {
        return item;
      }
      return !rules.map(item => item.source).includes(item.paramKey);
    });
  };

  const getAvailableTarget = (source, sourceDataType) => {
    return targetList.filter(item => {
      if (item.envKey === source) {
        return false;
      }
      return isDataTypeEqual(item.dataType, sourceDataType);
    });
  };

  const onSourceChange = (rowIndex, value) => {
    const newRules = [...rules];
    const source = value;
    const param = sourceList.find(item => item.paramKey === source);
    newRules[rowIndex].target = '';
    newRules[rowIndex].sourceDataType = param.dataType;
    newRules[rowIndex].sourceType = param.sourceType;
    setRules(newRules);
    onChange?.(newRules);
  };

  return (
    <RuleSetting>
      <RuleSettingHead>
        <RuleSettingTr>
          {columns.map(column => (
            <RuleSettingTd key={column.prop}>{column.name}</RuleSettingTd>
          ))}
          <RuleSettingTd className="delete-td" />
        </RuleSettingTr>
      </RuleSettingHead>
      <RuleSettingBody>
        {rules.map((rule, rowIndex) => (
          <RuleSettingTr key={rowIndex}>
            {columns.map(column => {
              if (column.prop === 'source') {
                return (
                  <RuleSettingTd key={column.prop}>
                    <Select
                      value={rule.source}
                      size="small"
                      onChange={(value) => onSourceChange(rowIndex, value)}
                      style={{ width: '100%' }}
                    >
                      {getAvailableSource(rule.source).map(item => (
                        <Select.Option key={item.paramKey} value={item.paramKey}>
                          {item.paramName}
                        </Select.Option>
                      ))}
                    </Select>
                  </RuleSettingTd>
                );
              }
              if (column.prop === 'sourceDataType') {
                return (
                  <RuleSettingTd key={column.prop}>
                    <DataTypeDisplay dataType={rule.sourceDataType} />
                  </RuleSettingTd>
                );
              }
              if (column.prop === 'target') {
                return (
                  <RuleSettingTd key={column.prop}>
                    <Select
                      value={rule.target}
                      size="small"
                      onChange={(value) => onTargetVarChange(rowIndex, value)}
                      style={{ width: '100%' }}
                    >
                      {getAvailableTarget(rule.source, rule.sourceDataType).map(item => (
                        <Select.Option key={item.envKey} value={item.envKey}>
                          <OptionLabel>
                            <OptionValue>{item.envKey}</OptionValue>
                            <OptionName>{item.envName}</OptionName>
                          </OptionLabel>
                        </Select.Option>
                      ))}
                    </Select>
                  </RuleSettingTd>
                );
              }
              return null;
            })}
            <RuleSettingTd className="delete-td">
              <DeleteOutlined onClick={() => removeRule(rowIndex)} />
            </RuleSettingTd>
          </RuleSettingTr>
        ))}
      </RuleSettingBody>
      <RuleSettingFoot>
        <Button size="small" type="primary" onClick={addRule}>
          {addText || '新增入参'}
        </Button>
      </RuleSettingFoot>
    </RuleSetting>
  );
};

export default OutputRuleSetting; 